package com.yadang.controller;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
public class DownloadController {

    @GetMapping("/download")
    public ResponseEntity<?> downloadFile() throws IOException {

        // 指定要下载的文件路径
        String filePath = "/path_to_your_file/file.csv";
        File file = new File(filePath);

        // 检查文件是否存在并且可读
        if (!file.exists() || !file.canRead()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件下载失败！"); // 返回404状态
        }

        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

        // 设置content type为CSV，你也可以根据需要设置其他的content type
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=" + file.getName())
                .contentType(MediaType.parseMediaType("application/csv"))
                .contentLength(file.length())
                .body(resource);
    }
}
